
import Vue from 'vue'
import axios from 'axios'
import { Toast ,Indicator } from 'mint-ui';
import router from '../../router/index'
axios.defaults.withCredentials = true
const $A = {
    /* 后台接口基础URL **/ 
    baseUrl:["http://autobuild.jiguantong.com:8087"],
    /* 过期重置URL **/ 
    Url:['http://autobuild.jiguantong.com/enterpriseWebApp/#'],
    Go,
    ST,
    GT,
    DC,
    SL,
    GF,
    MS,
    GUP,
    FU,
    GS,
    SS,
    AL,
    getUUID,
    comData,//公共数据
}
// http request interceptor
axios.interceptors.request.use(
  config => {
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
// http response interceptor
axios.interceptors.response.use(
  response => {
    const res = response.data || {}
    if(res.code && res.code == 200){
      return Promise.resolve(res)
    }else{
      // Toast({
      //   message: res.msg,
      //   position: 'middle',
      //   duration: 2000,
      // });
      return Promise.reject(res)
    }
  },
  error => {
    // Toast({
    //   message: error.response && error.response.data,
    //   position: 'middle',
    //   duration: 2000
    // });
    return Promise.reject(error.response.data)
  }
);
/*
* Author Mr Lan
* Created At 2019/09/10 16:54:32
* Name: Go.
* Parameter description and usage
* params:
*   M : The methods of request include get,post,delete,put, and file.
*   U : Requested address.
*   P : Parameters to request.
*   I : Base address.
*   Ty : It's only valid if the request is in file format, which means responsType.
* There is another mysterious use:
*   When the parameter I is less than 0, the request does not take the token parameter, and the basic address is the corresponding absolute value of the basic address
*
*/
async function Go(M='get',U,P={},I=0,Ty='arraybuffer',H){

  // if(M.toLowerCase() == M && (!sessionStorage.getItem('userInfo') || !sessionStorage.getItem('orgInfo'))){
  //   $A.ReLogin();
  //   return;
  // }
  let A = M;
  [U,M] = [HU(U,Math.abs(I)),M.toLowerCase()]
  return new Promise(function(resolve, reject) {
    let D = {
      method: M == 'fileg' ? 'get' : (M == 'filep'?'post':M),
      url: U
    },
    T = GT("token")
    M == 'get' && (D['params'] = P )
    M == 'filep' && ([D['data'], D['responseType']] = [P, Ty])
    M == 'fileg' && ([D['params'], D['responseType']] = [P, Ty])
    M != 'get' && M != 'fileg' && M != 'filep' && ( D['data'] = P );
    if(A.toLowerCase() == A){
      D['headers'] = {}
      // D['headers']['orgId'] = $A.GS('orgInfo')['orgId'];
      // D['headers']['type'] = $A.GS('orgInfo')['type'];
      D['headers']['token'] = $A.GS('userInfo')['token']
    }

    I >= 0 && H && (D['headers'] = H)//Object.assign(D['headers'],H) //([D['headers'],D['headers']['Authorization']] = [{},T])
    resolve(axios(D));
  });
}
/*
* Author Mr Lan
* Created At 2019/09/10 17:08:11
* Name: HU.
* Parameter description and usage
* params:
*   U : URL suffix
*   I : Subscript of the base address
* Splice complete URL
*/
function HU(U,I=0){
  if(U.startsWith('http://') || U.startsWith('https://') || U.startsWith('///')){
      return U;
    }else{
      return `${$A.baseUrl[I]}${U}`;
    }
}
/*
* Author Mr Lan
* Created At 2019/09/10 17:15:42
* Name: GT.
* Parameter description and usage
* params:
*   n : token name
* Get token with name n
*/
function GT(n){
    return 'c4367705-7cf5-4823-916c-c28702d41ec8'
    let v = sessionStorage.getItem(n)
    return v && JSON.parse(sessionStorage.getItem(n))
}
/*
* Author Mr Lan
* Created At 2019/09/10 17:19:03
* Name: ST.
* Parameter description and usage
* params:
*   n : token name
* Set token with name n,name of value
*/
function ST(n,v){
    sessionStorage.setItem(n, JSON.stringify(v));
}
/*
* Author Mr Lan
* Created At 2019/09/10 17:40:22
* Name: deepClone.
* Parameter description and usage
* params:
*   data : Data that requires deep cloning
* deep cloning
*/
function DC(data={}){
  return JSON.parse(JSON.stringify(data));
}
/*
* Author Mr Lan
* Created At 2019/09/10 17:55:36
* Name: SL.
* Parameter description and usage
* params:
*   T : The name of the loading
*   T : The type of the loading
* show loading
*/
function SL(T='',I=0){
  let typeList = ['snake','fading-circle','double-bounce','triple-bounce']
  Indicator.open({
    text: T,
    spinnerType: typeList[I]
  });
}
/*
* Author Mr Lan
* Created At 2019/09/11 15:25:12
* Name: MS.
* Parameter description and usage
* params:
*   M : The name of the message
*   T : The type of the message
*   M : The duation of the message
* show Tips
*/
function MS(M='提示信息！',P='middle',D=2000){
  Toast({
    message: M,
    position: P,
    duration: D,
    className:'lan-toast'
  });
}

/*
* Author Mr Lan
* Created At 2019/09/10 18:30:14
* Name: GF.
* Parameter description and usage
* params:
*   T : timestamp
*   R : Time format
* Get the time in the appropriate format
*/
function GF(T,R){
  try {
    let Tn = new Date(parseInt(T || new Date().getTime()))
    let [Y,M,D,H,Mi,S] = [Tn.getFullYear(),Tn.getMonth()+1,Tn.getDate(),Tn.getHours(),Tn.getMinutes(),Tn.getSeconds()]
    R.includes('yyyy') && (R = R.replace('yyyy',Y))
    R.includes('MM') && (R = R.replace('MM',(M+'').padStart(2,'0')))
    R.includes('M') && (R = R.replace('M',M))
    R.includes('dd') && (R = R.replace('dd',(D+'').padStart(2,'0')))
    R.includes('d') && (R = R.replace('d',D))
    R.includes('HH') && (R = R.replace('HH',(H+'').padStart(2,'0')))
    R.includes('H') && (R = R.replace('H',H))
    R.includes('mm') && (R = R.replace('mm',(Mi+'').padStart(2,'0')))
    R.includes('m') && (R = R.replace('m',Mi))
    R.includes('ss') && (R = R.replace('ss',(S+'').padStart(2,'0')))
    R.includes('s') && (R = R.replace('s',S))
    return R;
  } catch (error) {
    return ''
  }
}
/*
* Author Mr Lan
* Created At 2019/09/10 18:55:21
* Name: getUUID.
* usage
* Get random uuids
*/
function getUUID(){
  let d = new Date().getTime();
  let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      let r = (d + Math.random()*16)%16 | 0;
      d = Math.floor(d/16);
      return (c=='x' ? r : (r&0x7|0x8)).toString(16);
  });
  return uuid;
}
/*
* Author Mr Lan
* Created At 2019/09/11 9:01:02
* Name: GUP.
* usage
* Get the parameters after the url
*/
function GUP(){
  let [N,ps,P] = [self != top,window.location.href.split('?'),{}]
  if(N){
    return router.query
  }
  ps[1] && ([ps[1],ps] = [ps[1],ps[1].split('&')])
  for(let i=ps.length;i--;){
    let O = ps[i].split('=')
    O && O[0] && O[1] && (P[O[0]] = decodeURI(O[1]))
  }
  return P
}

/*
* Author Mr Lan
* Created At 2019/09/28 14:40:02
* Name: FU.
* usage
* Parameter description and usage
* params:
*   F : file stream
*   CB : callback function ,you will get the access to the address
*   U : The custom URL
*   P : A way to monitor the progress of an upload , you will get a number which ranges from 0 to 1
*
*/
async function FU(F,CB=(o)=>o,U='',P=(o)=>o){
  const fd = new FormData();
  fd.append('file', F, F.name);
  const xhr = new XMLHttpRequest();
  xhr.open('post', U || `${$A.baseUrl[0]}/safety/system/upload`, true);
  xhr.withCredentials = true;
  xhr.setRequestHeader("orgId",$A.GS('orgInfo')['orgId']); // 可以定义请求头带给后端
  xhr.setRequestHeader("type",$A.GS('orgInfo')['type']);
  //控制进度条的
  xhr.upload.addEventListener('progress', (evt) => {
    let progress = Math.round((evt.loaded) * 100 / evt.total);
    P && P(progress);
  }, false)
  xhr.addEventListener('load', (e) => {
    if (e.target.status !== 200) {
      return
    }
    if (e.target.status === 200) {
      let rs = JSON.parse(e.target.response || 'null')
      rs.body && CB(`${$A.baseUrl[0]}/safety/system/download?fileUrl=${rs.body}`)
    }
  }, false)
  xhr.send(fd)
}
/*
* Author Mr Lan
* Created At 2019/11/11 18:55:21
* Name: SS.
* usage
* encryption and  decryption，when data stored in sessionstorage
*/
function SS(N,D){
  D = JSON.stringify(D)
  let A = []
  for(let i = 0 ; i < D.length ; i++){
    A.push(D[i].charCodeAt())
  }
  sessionStorage.setItem(N,A.join('&'))
}
/*
* Author Mr Lan
* Created At 2019/11/11 18:55:21
* Name: GS.
* usage
* encryption and  decryption，when data stored in sessionstorage
*/
function GS(N){
  let S
  try {
    S = sessionStorage.getItem(N)
    if((N == 'userInfo' || N == 'orgInfo') && !S){
      return null;
    }
    if(!S){
      return null;
    }

    let A = S.split('&'),M = '';
    for(let i = 0 ; i < A.length ; i++){
      M += String.fromCharCode(A[i])
    }
    return JSON.parse(M || null) ;
  } catch (error) {
    return null
  }
}



async function comData(str,params) {
  let obj = {
    async userList(params){return new Promise((resolve, reject) => {//人员
      // setTimeout(()=>{
      //    resolve([{userName:'张三',userId:'129335'}])
      // },100)
      let obj = {
        "pageNo":-1,
        "pageSize":0,
        "obj":{
          'orgId': $A.GS('orgInfo')['orgId']
        }
      }
      obj['obj'] = Object.assign(obj['obj'],params);
      $A.Go('post','/safety/users',obj).then(res=>{
        let data = res.body || [];
        for(let i=data.length;i--;){
          data[i]['userName'] = data[i]['fullName']
          data[i]['userId'] = data[i]['id']
        }
        resolve(data)
      })
    })},
    async userAllList(params){return new Promise((resolve, reject) => {//人员
      let obj = {
        "obj":{
          'category': '-1',
        }
      }
      obj['obj'] = Object.assign(obj['obj'],params)
      $A.Go('post','/safety/project/users',obj).then(res=>{
        let data = res.body || [];
        for(let i=data.length;i--;){
          data[i]['userName'] = data[i]['employeeName']
          data[i]['userId'] = data[i]['id']
        }
        resolve(data)
      })
    })},
    async roleList(params){return new Promise((resolve, reject) => {//角色

      let obj = {
        "pageNo":-1,
        "pageSize":0,
        "obj":{
          'orgId': $A.GS('orgInfo')['orgId'],
          'roleStatus':($A.GS('orgInfo')['type'] == 1 || $A.GS('orgInfo')['type'] == 0)?'1':'2'
        }
      }
      obj = params || obj;
      $A.Go('post','/safety/role/select',obj).then(res=>{
        let data = res.body || [];
        for(let i=data.length;i--;){
          data[i]['roleId'] = data[i]['id']
        }
        resolve(data)
      })
    })},
    async projectList(params){return new Promise((resolve, reject) => {//项目
      //
      let url = "/safety/project/allProject"
      let nowinfo = $A.GS('orgInfo')
      let obj =  {
        "orgId": nowinfo['orgId'],
        "type": nowinfo['type']  // 当前组织ID
      }
      if($A.GS("userInfo")['type'] == '1'){
        url = "/safety/project/projects"
      }
      obj = params || obj;
      $A.Go('post',url,{obj}).then(res=>{
        let data = res.body || [];
        for(let i=data.length;i--;){
          data[i]['projectId'] = data[i]['id']
        }
        if($A.GS("userInfo")['type'] != 1 && nowinfo['type'] == 1){
          data.unshift({projectId:nowinfo['orgId'],projectName:nowinfo['orgName']})
        }
        resolve(data)
      })
    })},
    async orgList(params){return new Promise((resolve, reject) => {//组织
      setTimeout(()=>{
         resolve([{orgName:'测试项目',orgId:'1'},{orgName:'上海中建东孚投资发展有限公司',orgId:'10941'}])
      },100)
    })},
    async employeeList(params){return new Promise((resolve, reject) => {//分包

      let obj = {
        "pageNo":-1,
        "pageSize":0,
        "obj":{
          'category': "1",
          // 'projectId': $A.GS('orgInfo')['orgId']
        }
      }
      if(!params || (params && (!params['orgId'] && !params['projectId']))){//没有传参数
        if($A.GS('orgInfo')['type'] == 1){
          obj.obj['projectId'] = $A.GS('orgInfo')['orgId']
        }else{
          obj.obj['orgId'] = $A.GS('orgInfo')['orgId']
        }
      }
      obj['obj'] = Object.assign(obj['obj'],params);
      $A.Go('post','/safety/corp/',obj).then(res=>{
        let data = res.body || [];
        for(let i=data.length;i--;){
          data[i]['employeeName'] = data[i]['name']
          data[i]['employeeId'] = data[i]['id']
        }
        resolve(data)
      })
    })},
    // userToken:await $A.Go('post','/safety/systemToken',{"appUserName": "QualitySystem","appPassword": "QualitySystem"}).then(res=>res),
    async userToken(params){return new Promise((resolve, reject) => {//token
      $A.Go('post','/safety/systemToken',{"appUserName": "QualitySystem","appPassword": "QualitySystem"}).then(res=>resolve(res.body))
    })},
    async partList(params){return new Promise((resolve, reject) => {//分部分项
      $A.Go('get','/safety/engineeringCategory/partialItems',{}).then(res=>{
        let data = res.body || [];
        // generateList(data)
        for(let i=0;i<data.length;i++){
          if(!data[i]['children'] || data[i]['children'].length <= 0){
            data.splice(i,1);
            i--;
          }
        }
        resolve(data)
      })
    })},
    async addressList(params){return new Promise((resolve, reject) => {//组织
      let data = require('./nation.json')
      resolve(data)
    })},
    async meetLook(params){return new Promise((resolve, reject) => {//token
      $A.Go('post','/safety/read/add',{"obj":{"businessId":params,"orgId":$A.GS('orgInfo')['orgId']}})
    })},
    async checkTypeList(params){return new Promise((resolve, reject) => {//检查类型
      //
      let nowinfo = $A.GS('orgInfo')
      let obj =  {
        "orgId": nowinfo['orgId'],
        "type": nowinfo['type'] , // 当前组织ID
        "current":-1,
        "size":0,
        "status":'0',
      }
      obj = params || obj;
      $A.Go('get','/safety/checkType/pageList',{obj}).then(res=>{
        let data = res.body.rows || [];
        resolve(data)
      })
    })},
    async problemTypeList(params){return new Promise((resolve, reject) => {//问题类型
      //
      let nowinfo = $A.GS('orgInfo')
      let obj =  {
        // 当前组织ID
        obj:{
          "orgId": nowinfo['orgId'],
        },
        pageNo: -1,
        pageSize: 0
      }
      obj = params || obj;
      $A.Go('post','/safety/problemItem/pageList',obj).then(res=>{
        let data = res.body.rows || [];
        resolve(data)
      })
    })},
  }
  return obj[str] && obj[str](params)
}
//auto login
async function AL(){
  $A.Go('GET','/safety/login',{appUserName:'210A0248'}).then(success=>{
    if(success.code == 200){
        let data = success.body
        $A.SS('userInfo',{
            corpId:data.corpId,
            corpName:data.corpName,
            employeeNumber:data.employeeNumber,
            employeeName:data.employeeName,
            userId:data.id,
            userName:data.fullName,
            id:data.id,
            orgId:data.orgId,
            orgName:data.orgName,
            type:data.orgType,
            tenantId:data.tenantId,
            userType:data.userType
        })
        $A.SS('orgInfo',{orgId:data.orgId,orgName:data.orgName,type:data.orgType})
    }
  },function(err){
      console.log(err)
  })
}




// To be determined
async function getPolicy(ext) {
  let timestamp = new Date().getTime()
  return new Promise(function(resolve, reject) {
    resolve(axios.get(Api.baseUrl[1]+'/businessCommonService/cloud/policy?dir='+ timestamp +'/',{ ext }));
  });
}

async function uploadfile(file,callback,progressfn) {
      var _this = this;
      //参数  file ，
      //const file = document.getElementById('upload').files[0]
      console.log(file);
      let cloudFile = {};
      cloudFile.fileName = file.name;
      cloudFile.fileExt = file.type;
      //cloudFile.folderId = _this.folderId;///???
      cloudFile.fileSize = file.size +'';
      getPolicy(file.name).then(({data}) => {
        const fd = new FormData();
        const {accessid, host, policy, signature, dir, saveName} = data;

        fd.append('OSSAccessKeyId', accessid);
        fd.append('policy', policy);
        fd.append('signature', signature);
        fd.append('key', dir + saveName);
        fd.append('success_action_status', 200);
        fd.append('file', file, saveName + file.type);
        const xhr = new XMLHttpRequest();
        xhr.open('post', host, true);
        //控制进度条的
        xhr.upload.addEventListener('progress', (evt) => {
          let progress = Math.round((evt.loaded) * 100 / evt.total);
          progressfn && progressfn(progress);

        }, false)
        xhr.addEventListener('load', (e) => {
            if (e.target.status !== 200) {
                return
            }
            if (e.target.status === 200) {


                  callback && callback(host +'/'+ dir + saveName);
                  console.log(host +'/'+ dir + saveName);
            }
        }, false)
        xhr.send(fd)
      })
  }
  async function uploadfileCloud(file,callback,progressfn) {
    var _this = this;
    //参数  file ，
    let cloudFile = {};
    cloudFile.fileName = file.name;
    cloudFile.fileExt = file.type;
    cloudFile.fileSize = file.size +'';
    let saveName = file.name;
    getPolicy(file.name).then(({data}) => {
      const fd = new FormData();
      const {accessid, host, policy, signature, dir} = data;

      fd.append('OSSAccessKeyId', accessid);
      fd.append('policy', policy);
      fd.append('signature', signature);
      fd.append('key', dir + saveName);
      fd.append('success_action_status', 200);
      fd.append('file', file, saveName);
      const xhr = new XMLHttpRequest();
      xhr.open('post', host, true);
      //控制进度条的
      xhr.upload.addEventListener('progress', (evt) => {
        let progress = Math.round((evt.loaded) * 100 / evt.total);
        progressfn && progressfn(progress);

      }, false)
      xhr.addEventListener('load', (e) => {
          if (e.target.status !== 200) {
              return
          }
          if (e.target.status === 200) {

                let obj = {
                  size:file.size,
                  type:file.type,
                  fileType:saveName.substr(saveName.lastIndexOf('.')+1),
                  name:saveName,
                }
                callback && callback(host +'/'+ dir + saveName,obj);
                console.log(host +'/'+ dir + saveName,obj);
          }
      }, false)
      xhr.send(fd)
    })
}





























export default $A;
